package com.example.a13001.shoppingmalltemplate.activitys;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.manager.DataManager;
import com.example.a13001.shoppingmalltemplate.modle.NoticeDetail;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.MyWebViewClient;
import com.example.a13001.shoppingmalltemplate.utils.NoticeDetailWebViewClient;
import com.example.a13001.shoppingmalltemplate.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class InformDetailActivity extends BaseActivity {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.tv_informdetail_title)
    TextView tvInformdetailTitle;
    @BindView(R.id.tv_informdetail_content)
    TextView tvInformdetailContent;
    @BindView(R.id.tv_informdetail_time)
    TextView tvInformdetailTime;
    @BindView(R.id.web_infordetail)
    WebView webInfordetail;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private NoticeDetail mNoticeDetail;
    private static final String TAG = "InformDetailActivity";
    private String safetyCode;
    private String code;
    private String timeStamp;
    private int noticeid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inform_detail);
        ButterKnife.bind(this);
        tvTitleCenter.setText("通知详情");
        mCompositeSubscription = new CompositeSubscription();
        manager = new DataManager(InformDetailActivity.this);
        safetyCode = MyUtils.getMetaValue(InformDetailActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timeStamp = Utils.getTimeStamp();
        noticeid = getIntent().getIntExtra("noticeid", 2);
        Log.e(TAG, "onCreate: " + noticeid);
        getNoticeDetail(AppConstants.COMPANY_ID, code, timeStamp, noticeid);

        setWebView();
    }

    @OnClick(R.id.iv_title_back)
    public void onViewClicked() {
        onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    /**
     * 获取会员通知列表
     *
     * @param companyid
     * @param code
     * @param timestamp
     * @return
     */
    public void getNoticeDetail(String companyid, String code, String timestamp, int noticeid) {

        mCompositeSubscription.add(manager.getNoticeDetail(companyid, code, timestamp, noticeid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NoticeDetail>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: " + mNoticeDetail.toString());
                        if (mNoticeDetail != null) {
                            tvInformdetailTitle.setText(mNoticeDetail.getNoticeTitle() != null ? mNoticeDetail.getNoticeTitle() : "");
                            tvInformdetailContent.setText(mNoticeDetail.getNoticeContent() != null ? mNoticeDetail.getNoticeContent() : "");
                            tvInformdetailTime.setText(mNoticeDetail.getNoticeAddtime() != null ? mNoticeDetail.getNoticeAddtime() : "");
                            webInfordetail.loadDataWithBaseURL(null, mNoticeDetail.getNoticeContent(), "text/html" , "utf-8", null);

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:请求失败 " + e.toString());


                    }

                    @Override
                    public void onNext(NoticeDetail noticeDetail) {
                        mNoticeDetail = noticeDetail;
                    }
                }));
    }

    private void setWebView() {

        WebSettings webSettings = webInfordetail.getSettings();
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);//能够执行javascript脚本

        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDefaultFontSize(46);
        //改写客户端UA
        String ua = webSettings.getUserAgentString();
        webSettings.setUserAgentString(ua.replace("Android", "tjtv5android"));
//        webview.addJavascriptInterface(new DemoJavaScriptInterface(Window.this, webview, model), "Tjtv5API");
        webInfordetail.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //阻止滚动条出现白边
//        if (!Utils.isNetworkAvailable(Window.this)){
//            webview.loadUrl("file:///android_asset/404.html");
//        }else{
        //加载URL
        webInfordetail.loadUrl("file:///android_asset/noticedetail.html");
        Log.e(TAG, "setWebView: "+"code=="+code+"==timeStamp=="+timeStamp+"==noticeid=="+noticeid);
        webInfordetail.setWebViewClient(new NoticeDetailWebViewClient(InformDetailActivity.this, AppConstants.COMPANY_ID, code, timeStamp,noticeid,"webview"));
//        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            webInfordetail.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        webInfordetail.clearCache(true);
//        webInfordetail.loadDataWithBaseURL("",mContent,"text/html" , "utf-8", null);
        String jsonUrl = MyUtils.getMetaValue(this, "companyJSON");
//        webInfordetail.loadUrl("file:///android_asset/content.html");
//        String jsonUrl = MyUtils.getMetaValue(this, "companyURL");
//        webInfordetail.loadUrl("javascript:GetJson('" + jsonUrl + "','" + 144 + "','" + 3 + "',"  + ")");
//        webInfordetail.loadUrl("javascript:GetJson('" + jsonUrl + "','" + "144" + "','" + "3" + "');");
        //设置Web视图
//        webInfordetail.setWebViewClient(new MyWebViewClient(DetailActivity.this,AppConstants.COMPANY_ID,mContent,"webview"));
//        clearWebViewCache();

    }

    public void clearWebViewCache() {
// 清除cookie即可彻底清除缓存
        CookieSyncManager.createInstance(InformDetailActivity.this);
        CookieManager.getInstance().removeAllCookie();
    }

    //Web视图
    private class webViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    /**
     * 循环遍历标签中的图片
     * js 语法
     */
    private void imgReset() {
        webInfordetail.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%';   " +
                "}" +
                "})()");
    }

    @Override
    public boolean onKeyDown(int keyCoder, KeyEvent event) {
        if (keyCoder == KeyEvent.KEYCODE_BACK && webInfordetail.canGoBack()) {
            webInfordetail.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCoder, event);
    }
}
